package com.fire.user.util;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fire.core.jkmodel.ReqDTO;
import com.fire.core.jkmodel.XmlMessageDTO;
import com.fire.core.util.AjaxResult;
import com.fire.core.util.GenratorNoHelper;
import com.fire.core.util.XmlMessageUtil;
import com.fire.user.constants.ErrorCodeConstants;
import com.fire.user.constants.JkConstants;

/**
 * 类描述：
 *
 * @author Aspire
 * @version 1.0
 */
@Component
public class JkWxUtils {
	private static Logger logger = Logger.getLogger(JkWxUtils.class);
	@Autowired
	private JkUtils jkUtils;


	private String getToken = "getWxAccessToken";
	private String getTicket = "getWxJsApiTicket";
	private String cmrh = "CMRH";

	public AjaxResult getJKAccessToken() {
		logger.info("调用金科接口获取AccessToken");
		return getTokenOrTicket(getToken);
	}

	public AjaxResult getJKTicket() {
		logger.info("调用金科接口获取JsApiTickets");
		return getTokenOrTicket(getTicket);
	}

	public AjaxResult getTokenOrTicket(String type) {
		jkUtils.getConfigure();
		ReqDTO<String> reqDTO = new ReqDTO<>();
		Long timestamp = System.currentTimeMillis();
		String requestId = GenratorNoHelper.generateRequestId() + timestamp;
		if (type.equals(getToken)) {
			reqDTO.setTransCode(getToken);
		} else {
			reqDTO.setTransCode(getTicket);
		}
		reqDTO.setPartnerCode(jkUtils.getPARTNER_CODE());
		reqDTO.setRequestId(requestId);
		reqDTO.setTimestamp(timestamp);
		reqDTO.setReqData(cmrh);

		String where = "mit/user/" + reqDTO.getTransCode();
		String what = reqDTO.getTransCode();
		String responseStr;
		try {
			responseStr = jkUtils.postRequest(reqDTO, requestId, where, what, "");
		} catch (Exception e) {
			logger.error("调金科接口错误===>" + e);
			return new AjaxResult(ErrorCodeConstants.JK_INTERFACE_FAIL, "金科系统内部错误", "金科系统内部错误");
		}
		XmlMessageDTO xmlMessageDTO = XmlMessageUtil.parseXml(responseStr);
		boolean flag = jkUtils.checkSign(xmlMessageDTO);
		AjaxResult ajaxResult = new AjaxResult();
		// 验证签名是否合法
		if (flag) {
			JSONObject resultObj = JSON.parseObject(xmlMessageDTO.getContent());
			if (JkConstants.JK_RESULT_SUCCESS_CODE.equals(resultObj.getString(JkConstants.JK_RESULT_CONTENT_RESCODE))) {
				String resData = resultObj.getString(JkConstants.JK_RESULT_CONTENT_RESDATA);
				ajaxResult.setContext(resData);
				ajaxResult.setStatus(ErrorCodeConstants.SUCCESS);
				ajaxResult.setMessage("获取成功");
				ajaxResult.setTips("获取成功");
			} else {
				String resultMsg = resultObj.getString(JkConstants.JK_RESULT_CONTENT_RESMSG);
				return new AjaxResult(ErrorCodeConstants.JK_INTERFACE_FAIL, resultMsg, resultMsg);
			}
		} else {
			return new AjaxResult(ErrorCodeConstants.SIGN_ERROR, "签名验证失败", "签名验证失败");
		}
		return ajaxResult;
	}
}
